package com.gzx.plugin.tjzy.modular.qianwen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gzx.plugin.tjzy.modular.qianwen.constant.IntentType;
import com.gzx.plugin.tjzy.modular.qianwen.service.IntentPromptService;
import com.gzx.plugin.tjzy.modular.qianwen.util.IntentPromptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import vip.xiaonuo.dev.api.DevDictApi;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 提示词助手
 */
@Slf4j
@Service
public class IntentPromptServiceImpl implements IntentPromptService {

    //读取nacos中的配置
    @Value("${qianwen.apiKey}")
    private String apiKey;

    private final DevDictApi devDictApi;

    public IntentPromptServiceImpl(DevDictApi devDictApi) {
        this.devDictApi = devDictApi;
    }

    // 用于缓存 dict 数据
    private static final Map<String, JSONArray> dictCache = new ConcurrentHashMap<>();

    //分析意图
    @Override
    public String analyzeIntent(String userMessage) {
        // 从缓存中获取数据
        JSONArray array = dictCache.get(IntentType.CALL_INTENT);
        if (array == null || array.isEmpty()) {
            refreshDictCache();
            array = dictCache.get(IntentType.CALL_INTENT);
            log.warn("字典缓存为空，从数据库获取数据");
        }
        String intent = IntentPromptUtil.analyzeIntent(userMessage, apiKey, array);
        log.info("说话人的意图是 {} ", intent);
        return intent;
    }

    /**
     * 定时任务：每 10 分钟刷新一次缓存
     */
    @Scheduled(fixedRate = 600000) // 10分钟 = 10 * 60 * 1000 毫秒
    public void refreshDictCache() {
        try {
            String dict = devDictApi.getDictByType(IntentType.CALL_INTENT);
            JSONArray array = JSON.parseArray(dict);
            dictCache.put(IntentType.CALL_INTENT, array);
            log.info("字典数据已刷新并缓存");
        } catch (Exception e) {
            log.error("刷新字典缓存失败", e);
        }
    }
}
